import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:flutter/widgets.dart';
import 'package:flutter_give/pages/Home/home_vm.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:oktoast/oktoast.dart';
import 'package:provider/provider.dart';
import 'package:pull_to_refresh/pull_to_refresh.dart';
import 'package:rapid_kit/rapid_kit.dart';

import '../../common_ui/common_style.dart';
import '../../repository/datas/TangeEqData.dart';
import '../../repository/datas/TangeEqEent.dart';
import '../../repository/datas/TangeEqFilter.dart';
import '../../utils/LogUtils.dart';
import '../../utils/constants.dart';
import '../../utils/sp_utils.dart';
import 'package:intl/intl.dart';

import '../subpackage/lookevent_page.dart';

/// 消息页面
class HotKeyPage extends StatefulWidget {
  const HotKeyPage({super.key});

  @override
  State<StatefulWidget> createState() {
    return HotKeyPageState();
  }
}

// _代表私有
class HotKeyPageState extends State<HotKeyPage> {
  // List<BannerItemData>? bannerList; - 使用状态管理
  // 创建一个 GlobalKey
  static final GlobalKey<HotKeyPageState> globalKey =
      GlobalKey<HotKeyPageState>();

  // 获取类
  HomeViewModel viewModel = HomeViewModel();

  // 上拉刷新-下拉加载0组件
  RefreshController refreshController = RefreshController();

  // 静态数据
  List<Map<String, dynamic>> DevicesList = [
    {'id': 0, 'name': '全部'},
    {'id': 1, 'name': '设备2'},
    {'id': 2, 'name': '设备3'},
    {'id': 3, 'name': '设备4'},
    {'id': 4, 'name': '设备5'},
    {'id': 5, 'name': '全部'},
    {'id': 6, 'name': '设备2'},
    {'id': 7, 'name': '设备3'},
    {'id': 8, 'name': '设备4'},
    //
  ];

  // 维护每个日期项的颜色状态
  List<Color> textColors = List.generate(30, (_) => Colors.black);

  // 创建一个 ScrollController
  final ScrollController _scrollController = ScrollController();

  String datetime = "";

  // 探鸽
  // 报警事件数据
  final List<Event> _events = [];
  static const int _pageSize = 30;
  DateTime _selectedDate = DateTime.now();
  final DateTime _todayDate = DateTime.now();
  late String _deviceId;

  @override
  void initState() {
    // TODO: implement initState
    super.initState();

    datetime = getdate();

    // 开启加载框
    // Loading.showLoading();

    // 执行时候-已经初始化了-没效果
    // initBannerData();

    // 使用状态管理
    // viewModel.initDio();

    // 默认选中今天
    int todayIndex = 29; // 今天的索引是29，因为是从现在开始往前推30天
    textColors[todayIndex] = Colors.blue; // 将今天的颜色设置为蓝色

    // 在初始化时将滚动位置设置到最右边
    WidgetsBinding.instance.addPostFrameCallback((_) {
      _scrollController.jumpTo(_scrollController.position.maxScrollExtent);
    });
  }

  @override
  void dispose() {
    // 记得在 dispose 时释放 ScrollController
    _scrollController.dispose();
    super.dispose();
  }

  String getdate() {
    // 获取当前日期和时间
    DateTime now = DateTime.now();

    // 获取年、月、日
    int year = now.year;
    int month = now.month;
    int day = now.day;

    // 对月份和日期进行补零操作
    String monthStr = month.toString().padLeft(2, '0');
    String dayStr = day.toString().padLeft(2, '0');

    // 打印结果
    print('今天的日期是：$year年$monthStr月$dayStr日');
    return '$year-$monthStr-$dayStr';
  }

  String operationDate(String timestampStr) {
    // 将字符串转换为整数类型的时间戳
    int timestamp = int.parse(timestampStr);

    // 将时间戳转换为DateTime对象
    DateTime dateTime = DateTime.fromMillisecondsSinceEpoch(timestamp * 1000);

    // 获取年、月、日、时、分、秒
    int year = dateTime.year;
    int month = dateTime.month;
    int day = dateTime.day;
    int hour = dateTime.hour;
    int minute = dateTime.minute;
    int second = dateTime.second;

    // 对时、分、秒进行补零操作
    String hourStr = hour.toString().padLeft(2, '0');
    String minuteStr = minute.toString().padLeft(2, '0');
    String secondStr = second.toString().padLeft(2, '0');

    // 返回格式化后的日期和时间
    return '$year-$month-$day $hourStr:$minuteStr:$secondStr';
  }

  // 重新加载
  void reloadData() {
    // 在这里实现重新加载数据的逻辑
    print("==============加载第二页数据=============");
    SystemChrome.setSystemUIOverlayStyle(const SystemUiOverlayStyle(
      statusBarColor: Color(0xFFffffff), // 设置状态栏颜色
      statusBarIconBrightness: Brightness.dark, // 设置状态栏图标亮度为暗色
    ));

    viewModel.tangeeqlist.clear();
    viewModel.getTANGEList();

    // 查询事件参数
    viewModel.getEventList(tag: "", date: datetime, deviceid: "");
  }

  @override
  Widget build(BuildContext context) {
    return ChangeNotifierProvider(
      create: (context) {
        return viewModel;
      },
      child: Scaffold(
        appBar: AppBar(
          // 设置背景颜色为白色
          backgroundColor: Colors.white,
          title: Text(
            '消息',
            style: TextStyle(fontWeight: FontWeight.w600, fontSize: 16.sp),
          ),
        ),
        body: SafeArea(
          child: Column(
            children: [
              // 不参与刷新和加载
              Consumer<HomeViewModel>(builder: (context, vm, child) {
                // LogUtils.w(vm.tangeeqlist);
                // LogUtils.e("9999999999999999999");
                // LogUtils.e(vm.keyList);
                return _branner(vm.tangeeqlist, vm.tangefilterList);
              }),
              Expanded(
                child: SmartRefresher(
                  controller: refreshController,
                  enablePullUp: true,
                  enablePullDown: true,
                  header: ClassicHeader(
                    //无特殊要求就可以用这个换下文案就行了
                    height: 45.0,
                    releaseText: '松开刷新',
                    refreshingText: '刷新中',
                    completeText: '刷新完成',
                    idleText: '下拉刷新',
                  ),
                  footer: ClassicFooter(
                    //无特殊要求就可以用这个换下文案就行了
                    loadStyle: LoadStyle.ShowWhenLoading,
                    completeDuration: Duration(microseconds: 50),
                    canLoadingText: '松开刷新',
                    noDataText: '没有更多数据啦',
                    loadingText: '刷新中',
                    idleText: '上拉加载',
                  ),
                  onLoading: () {
                    viewModel
                        .initEventData(tag: "", date: datetime, deviceid: "")
                        .then((value) => refreshController.loadComplete());
                  },
                  onRefresh: () {
                    LogUtils.w(datetime);

                    // 重置所有日期的颜色为黑色
                    textColors = List.generate(30, (_) => Colors.black);
                    // 将当前点击的日期颜色设置为蓝色
                    textColors[29] = Colors.blue;
                    // 下拉刷新回调
                    String date = getdate();
                    viewModel.tangeeventlist.clear();
                    viewModel.limit = 10;
                    viewModel.offset = 1;
                    viewModel.getEventList(tag: "", date: date, deviceid: "");
                    refreshController.refreshCompleted();
                  },
                  child: _buildHomeView(), // 列表参与刷新和加载
                ),
              ),
            ],
          ),
        ),
      ),
    );
  }

  Widget _buildHomeView() {
    return Consumer<HomeViewModel>(builder: (context, vm, child) {
      if (vm.tangeeventlist == null || vm.tangeeventlist!.isEmpty) {
        return _noDataView();
      } else {
        return _homeListView();
      }
    });
  }

  Widget _noDataView() {
    return Center(
      child: Column(
        mainAxisAlignment: MainAxisAlignment.center,
        children: [
          Spacer(),
          Image.asset(
            'assets/app_img/eventnodata.png', // 替换为你的图片路径
            width: 150,
            height: 150,
          ),
          SizedBox(height: 5),
          Text("暂无数据",style: TextStyle(color: Color(0xFF656467)),),
          Spacer(),
        ],
      ),
    );
  }

  Widget _homeListView() {
    return Consumer<HomeViewModel>(builder: (context, vm, child) {
      return Container(
        color: Color(0xFFf1f1f1),
        // height: double.infinity,
        child: ListView.builder(
          // 内部自己计算高度-不然SingleChildScrollView没有高度，渲染不出来
          shrinkWrap: true,
          // 关闭ListView滚动-使用SingleChildScrollView滚动
          // 不然会出现 滚动下面轮播图不懂
          // 滚动轮播图-才会全部滚动-因为使用的是SingleChildScrollView滚动
          physics: NeverScrollableScrollPhysics(),
          itemBuilder: (context, index) {
            return _ListItemView(vm.tangeeventlist[index], index);
          },
          itemCount: vm.tangeeventlist?.length ?? 0,
        ),
      );
    });
  }

  // 每一项 自己
  Widget _ListItemView(TangeEqEent item, int index) {
    return GestureDetector(
      onTap: () {
        print("====================跳转页面==================");
        Navigator.push(
            context,
            MaterialPageRoute(
                builder: (context) =>
                    LookeventPage(imghttp:item?.image ?? "",deviceName: item?.deviceName ?? "查看图片",)));
      },
      child: Container(
        margin: EdgeInsets.only(
          top: 5,
          bottom: 10,
          left: 10,
          right: 10,
        ),
        padding: EdgeInsets.only(
          top: 13,
          bottom: 13,
          left: 10,
          right: 10,
        ),
        decoration: BoxDecoration(
            color: Color(0xFFFFFFFF),
            border: Border.all(color: Color(0xFFf6f6f6), width: 0.5),
            borderRadius: BorderRadius.all(Radius.circular(10))),
        child: Row(
          crossAxisAlignment: CrossAxisAlignment.start,
          children: [
            // 左边部分
            Expanded(
              child: Column(
                crossAxisAlignment: CrossAxisAlignment.start,
                children: [
                  Text(
                    "${item.deviceName}",
                    style: TextStyle(color: Color(0xFF1e1f22), fontSize: 16.sp,fontWeight: FontWeight.w600),
                  ),
                  SizedBox(height: 5),
                  Text(
                    // "${index + 1}${item.tag?.msg}",
                    "${item.tag?.msg}",
                    style: TextStyle(color: Color(0xFF737272)),
                  ),
                  SizedBox(height: 7),
                  Text(
                    operationDate("${item.time}") ?? "",
                    style: TextStyle(color: Color(0xFF737272)),
                  ),
                ],
              ),
            ),
            SizedBox(width: 20), // 中间留点间隙
            // 右边部分
            ClipRRect(
              borderRadius: BorderRadius.circular(5),
              child: Image.network(
                item.image ??
                    "https://img0.baidu.com/it/u=2835430233,1384716354&fm=253&fmt=auto&app=138&f=JPEG?w=748&h=500",
                width: 125,
                height: 75,
                fit: BoxFit.fill,
              ),
            ),
          ],
        ),
      ),
    );
  }

  Widget _branner(List<TangeEqData> eqdata, List<TangeEqFilter>? filterdata) {
    // LogUtils.w(eqdata);
    return Column(
      children: [
        // 筛选
        Padding(
          padding: const EdgeInsets.only(
              top: 8.0, left: 8.0, right: 8.0, bottom: 15.0),
          child: Row(
            mainAxisAlignment: MainAxisAlignment.spaceAround,
            children: [
              // 左边：全部设备
              GestureDetector(
                onTap: () {
                  SpUtils.saveString(Constants.BUT_PROP_TYPR, "${1}");

                  // 传递数据
                  LogUtils.w(eqdata);
                  // 在这里添加点击事件的处理逻辑
                  botttomshow(context, '全部设备', eqdata, () {
                    setState(() {});
                    SpUtils.getString(Constants.BUT_PROP_TYPR).then((value) => {
                          if (value == '1')
                            {
                              SpUtils.getString(Constants.BUT_PROP_PRICE).then(
                                (value) => {
                                  showToast('全部设备被点击${value}'),
                                  viewModel.tangeeventlist.clear(),
                                  viewModel.limit = 10,
                                  viewModel.offset = 1,
                                  if (value == "99999")
                                    {
                                      datetime = getdate(),
                                      // 重置所有日期的颜色为黑色
                                      textColors = List.generate(
                                          30, (_) => Colors.black),
                                      // 将当前点击的日期颜色设置为蓝色
                                      textColors[29] = Colors.blue,
                                      viewModel.getEventList(
                                          tag: "",
                                          date: datetime,
                                          deviceid: ""),
                                    }
                                  else
                                    {
                                      viewModel.getEventList(
                                          tag: "",
                                          date: datetime,
                                          deviceid: value),
                                    },
                                  Navigator.pop(context),
                                },
                              )
                            }
                        });
                  });
                },
                child: Row(
                  mainAxisAlignment: MainAxisAlignment.center,
                  children: [
                    Text(
                      '全部设备',
                      style: TextStyle(fontSize: 16.sp),
                    ),
                    Icon(Icons.arrow_drop_down),
                  ],
                ),
              ),
              // 右边：全部类型
              GestureDetector(
                onTap: () {
                  // 在这里添加点击事件的处理逻辑
                  SpUtils.saveString(Constants.BUT_PROP_TYPR, "2");
                  showToast('全部类型被点击');
                  LogUtils.w(filterdata?.length);
                  botttomfiltershow(context, '全部类型', filterdata, () {
                    SpUtils.getString(Constants.BUT_PROP_TYPR).then((value) => {
                          if (value == '2')
                            {
                              SpUtils.getString(Constants.BUT_FILTER_PRICE)
                                  .then(
                                (value) => {
                                  showToast('全部类型被点击${value}'),
                                  viewModel.tangeeventlist.clear(),
                                  viewModel.limit = 10,
                                  viewModel.offset = 1,
                                  if (value == "99999")
                                    {
                                      datetime = getdate(),
                                      // 重置所有日期的颜色为黑色
                                      textColors = List.generate(
                                          30, (_) => Colors.black),
                                      // 将当前点击的日期颜色设置为蓝色
                                      textColors[29] = Colors.blue,
                                      viewModel.getEventList(
                                          tag: "",
                                          date: datetime,
                                          deviceid: ""),
                                    }
                                  else
                                    {
                                      viewModel.getEventList(
                                          tag: value,
                                          date: datetime,
                                          deviceid: ""),
                                    },
                                  Navigator.pop(context),
                                },
                              )
                            }
                        });
                  });
                },
                child: Row(
                  mainAxisAlignment: MainAxisAlignment.center,
                  children: [
                    Text('全部类型', style: TextStyle(fontSize: 16.sp)),
                    Icon(Icons.arrow_drop_down),
                  ],
                ),
              ),
            ],
          ),
        ),
        // 日期
        Padding(
          padding: const EdgeInsets.all(8.0),
          // padding: const EdgeInsets.fromLTRB(8, 8, 8, 12),
          child: SingleChildScrollView(
            scrollDirection: Axis.horizontal, // 设置为水平滚动
            controller: _scrollController, // 设置 ScrollController
            child: Row(
              mainAxisAlignment: MainAxisAlignment.spaceAround,
              children: List.generate(30, (index) {
                // 获取最近30天的日期
                final now = DateTime.now();
                final date = now.subtract(Duration(days: 29 - index));

                return GestureDetector(
                  onTap: () {
                    // 点击时改变颜色
                    setState(() {
                      // 重置所有日期的颜色为黑色
                      textColors = List.generate(30, (_) => Colors.black);
                      // 将当前点击的日期颜色设置为蓝色
                      textColors[index] = Colors.blue; // 你可以选择其他颜色
                    });

                    // 使用 padLeft 来补零
                    String month = date.month.toString().padLeft(2, '0');
                    String day = date.day.toString().padLeft(2, '0');

                    // 打印当天的数据
                    showToast('点击了 ${date.year}-${month}-${day}');

                    datetime = "${date.year}-${month}-${day}";
                    viewModel.tangeeventlist.clear();
                    viewModel.limit = 10;
                    viewModel.offset = 1;
                    viewModel.getEventList(
                        tag: "", date: datetime, deviceid: "");
                  },
                  child: Padding(
                    padding: const EdgeInsets.symmetric(horizontal: 8.0),
                    // 添加一些间距
                    child: Column(
                      children: [
                        // 星期
                        Text(
                          '星期${[
                            '日',
                            '一',
                            '二',
                            '三',
                            '四',
                            '五',
                            '六'
                          ][date.weekday % 7]}',
                          style:
                              TextStyle(fontSize: 12, color: textColors[index]),
                        ),
                        // 几号
                        Text(
                          '${date.day}',
                          style: TextStyle(
                              fontSize: 16,
                              fontWeight: FontWeight.bold,
                              color: textColors[index]),
                        ),
                      ],
                    ),
                  ),
                );
              }),
            ),
          ),
        ),
        // 日期选择
        Padding(
          padding: const EdgeInsets.all(5),
          child: GestureDetector(
            onTap: () async {
              // 计算一个月前的日期
              DateTime now = DateTime.now();
              DateTime oneMonthAgo = now.subtract(Duration(days: 30));

              // 弹出日期选择框
              DateTime? selectedDate = await showDatePicker(
                context: context,
                initialDate: DateTime.now(),
                firstDate: oneMonthAgo,
                // 从一个月前的日期开始
                lastDate: now,
                // 到今天的日期结束
                locale: const Locale('zh', 'CN'), // 设置为中文
              );

              // 如果用户选择了日期，则返回选择的日期
              if (selectedDate != null) {
                // 使用 DateFormat 格式化日期为 "年月日" 格式
                String formattedDate =
                    DateFormat('yyyy-MM-dd').format(selectedDate);
                showToast('选择的日期是: $formattedDate');

                String day = formattedDate.substring(8, 10);
                int dayInt = int.parse(day);

                final now = DateTime.now();

                // 生成从今天开始往前30天的日期列表
                final dates = List.generate(30, (index) => now.subtract(Duration(days: index))).reversed.toList();

                // 打印所有日期
                for (var date in dates) {
                  print(date);
                  print(date.day);
                }

                // 找到特定日期的下标位置
                final index = dates.indexWhere((date) => date.day == dayInt);

                LogUtils.w(index);

                // 重置所有日期的颜色为黑色
                textColors = List.generate(30, (_) => Colors.black);
                // 将当前点击的日期颜色设置为蓝色
                textColors[index] = Colors.blue;


                viewModel.tangeeventlist.clear();
                datetime = formattedDate;
                viewModel.tangeeventlist.clear();
                viewModel.limit = 10;
                viewModel.offset = 1;
                viewModel.getEventList(tag: "", date: datetime, deviceid: "");
              }
            },
            child: Row(
              mainAxisAlignment: MainAxisAlignment.center,
              children: [
                Icon(
                  Icons.keyboard_arrow_down_outlined, // 左箭头图标
                  size: 24.0,
                  color: Colors.black, // 图标颜色
                ),
              ],
            ),
          ),
        )
      ],
    );
  }
}
